package com.example.petstore.controller;

import com.example.petstore.common.CommonResponse;
import com.example.petstore.domain.*;
import com.example.petstore.service.*;
import com.example.petstore.util.ZFBqrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SessionAttributes({"loginUser", "tempOrderId"})
@Validated
@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private LineItemService lineItemService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private CartService cartService;
    @Autowired
    private ProductService productService;

    /**
     * 获取全部订单
     * @param model
     * @return
     */
    @GetMapping("/user/findAllOrder")
    @ResponseBody
    public CommonResponse userGetAllOrder(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
//        return orderService.userFindAllOrder("wjh");
        return orderService.userFindAllOrder(user.getUsername());
    }

    /**
     * 获取未收发货的订单
     * @param model
     * @return
     */
    @GetMapping("/user/findNoShipOrder")
    @ResponseBody
    public CommonResponse userFindNoShipOrder(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        return orderService.userFindNoShipOrder(user.getUsername());
    }

    /**
     * 获取已发货的订单
     * @param model
     * @return
     */
    @GetMapping("/user/findShipOrder")
    @ResponseBody
    public CommonResponse<List<Order>> userFindShipOrder(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        return orderService.userFindShipOrder(user.getUsername());
    }

    /**
     * 获取未付款的订单
     * @param model
     * @return
     */
    @GetMapping("/user/findNoPayOrder")
    @ResponseBody
    public CommonResponse<List<Order>> userFindNoPayOrder(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        return orderService.userFindNoPayOrder(user.getUsername());
    }

    /**
     * 获取用户未收到货的订单
     * @param model
     * @return
     */
    @GetMapping("/user/findNoGetOrder")
    @ResponseBody
    public CommonResponse findNoGetOrder(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        return orderService.userFindNoGetOrder(user.getUsername());
    }

    /**
     * 用户进入查看所有订单页面
     * @param model
     * @return
     */
    @GetMapping("/user/order")
    public String userOrderForm(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        CommonResponse commonResponse = orderService.getUserOrderList(user.getUsername());
        System.out.println(commonResponse.getData());
        model.addAttribute("orderList", commonResponse.getData());
//        到用户订单页面
        return "user/order";
    }

    /**
     * 进入某个订单详细页面
     * @param orderId
     * @param model
     * @return
     */
    @GetMapping("/user/orderForm")
    public String oderForm(String orderId, ModelMap model){
        User user =(User) model.getAttribute("loginUser");
        CommonResponse commonResponse = orderService.getOrderByOrderId(orderId);
        if(commonResponse.isSuccess()) {
            Order order = (Order) commonResponse.getData();
            model.addAttribute("order", order);
            List<LineItem> lineItems = lineItemService.getLineItemsByOrderId(order.orderid);
            model.addAttribute("lineItems", lineItems);

            return "user/showOrder";
        }else{
            return "/index";
        }
    }

    /**
     * 对某个item立即购买，默认买一个
     * @param itemId
     * @param model
     * @return
     */
    @RequestMapping("/user/buyItem")
    public String userBuyItemAtOnce(String itemId, ModelMap model) {
        User user =(User) model.getAttribute("loginUser");
        if(user == null){
            model.addAttribute("errorMsg", "您尚未登录！");

            CommonResponse commonResponse = itemService.getItemByItemid(itemId);
            Item item = (Item) commonResponse.getData();
            Product product = productService.getProductByProductId(item.getProductid());
//            System.out.println(product);
            model.addAttribute("product", product);
            CommonResponse commonResponse1 = itemService.getItemByItemid(itemId);
            model.addAttribute("item", commonResponse1.getData());
//            System.out.println(commonResponse.getData());
//            到item详情页面
            return "catalog/item";
        }
        //  默认买一个
        CommonResponse commonResponse = orderService.userBuyItemAtOnce(user.getUsername(), itemId, 1);
        if(commonResponse.isSuccess()){
            Order order = (Order) commonResponse.getData();
            model.addAttribute("order", order);
            model.addAttribute("tempOrderId", order.getOrderid());
            List<LineItem> lineItems = lineItemService.getLineItemsByOrderId(order.orderid);
            model.addAttribute("lineItems", lineItems);
            return "cartOrder/confirmOrder";
        }

        commonResponse = itemService.getItemByItemid(itemId);
        Item item = (Item) commonResponse.getData();
        model.addAttribute("errorMsg", commonResponse.getMessage());
        Product product = productService.getProductByProductId(item.getProductid());
//            System.out.println(product);
        model.addAttribute("product", product);
        CommonResponse commonResponse1 = itemService.getItemByItemid(itemId);
        model.addAttribute("item", commonResponse1.getData());
//            System.out.println(commonResponse.getData());
//            到item详情页面
        return "catalog/item";
    }

    /**
     * 从购物车付款
     * @param model
     * @return
     */
    @GetMapping("/user/newOrder")
    public String userNewOrder(ModelMap model){
        User user = (User) model.getAttribute("loginUser");
        CommonResponse commonResponse = orderService.userBuyCartItem(user.getUsername());
        if(commonResponse.isSuccess()){
            Order order = (Order) commonResponse.getData();
            model.addAttribute("order", order);
            model.addAttribute("tempOrderId", order.getOrderid());
            List<LineItem> lineItems = lineItemService.getLineItemsByOrderId(order.orderid);
            model.addAttribute("lineItems", lineItems);
            return "cartOrder/confirmOrder";
        }
        model.addAttribute("errorMsg", commonResponse.getMessage());
//        再购物车界面

//        User user = (User) model.getAttribute("loginUser");
        commonResponse = cartService.getUerCartItemList(user.getUsername());
        if(commonResponse.isSuccess()){
            HashMap<CartItem, Item> cartItemItemHashMap = new HashMap<>();
            for(CartItem cartItem : (List<CartItem>)commonResponse.getData()) {
                Item item = (Item) itemService.getItemByItemid(cartItem.getItemid()).getData();
                cartItemItemHashMap.put(cartItem, item);
            }
            if(cartItemItemHashMap.isEmpty())
                model.addAttribute("cartItemListMap", null);
            else
                model.addAttribute("cartItemListMap", cartItemItemHashMap);
//            到购物车页面
            return "cartOrder/cart";
        }
        model.addAttribute("errorMsg", commonResponse.getMessage());
//        todo:原页面
        return "catalog/main";
    }

    /**
     * 进入支付界面
     * @param order
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/user/payForm")
    public String payForm(@Validated @ModelAttribute Order order, BindingResult bindingResult, ModelMap model) throws Exception{
        if(bindingResult.hasErrors() ){

            StringBuilder ts = new StringBuilder();
            for(ObjectError err: bindingResult.getAllErrors()){
                ts.append(err.getDefaultMessage());
            }
            System.out.println(ts);
            model.addAttribute("errorMsg", ts);
            return "cartOrder/confirmOrder";
        }
        System.out.println(order);

//        int tempId = order.getOrderid();
//        order.setOrderid(0);
        orderService.updateOrderByOrderId(order);
//        System.out.println(order);
        Map map = ZFBqrUtil.getQR(order.getTotalprice());
//       将outTradeNo存进数据库
        System.out.println((String)map.get("outTradeNo"));
        System.out.println(order.getOrderid());
        orderService.updateOutTradeNoByOrderId((String)map.get("outTradeNo"),order.getOrderid());
//        System.out.println(map);
        model.addAttribute("qrCode", map.get("qrcode"));
        model.addAttribute("outTradeNo", map.get("outTradeNo"));
//        到支付宝页面
        return "user/payForm";
    }

    /**
     * 完成订单
     * @param outTradeNo
     * @param model
     * @return
     * @throws Exception
     */
    @GetMapping("/user/finishPay")
    @ResponseBody
    public CommonResponse finishPay(String outTradeNo, ModelMap model)throws Exception{
//        获取订单支付状态
        Object object = ZFBqrUtil.getPayStatue(outTradeNo);
        if(object == null || ((String)object).equals("0.00")){
            return CommonResponse.creatForError("您尚未付款!");
        }
        int orderId = (int) model.getAttribute("tempOrderId");
        boolean result = orderService.finishPay(orderId);
        if(result){
            return CommonResponse.creatForSuccessMessage("支付成功");
        }else{

            return CommonResponse.creatForError("系统出错了!");
        }
    }

    /**
     * 取消支付
     * @param model
     * @return
     */
    @GetMapping("/user/cancelPay")
    public String cancelPay(ModelMap model){
        int orderId = (int) model.getAttribute("tempOrderId");
        boolean result = orderService.cancelPay(orderId);
        if(result){
            model.addAttribute("msg", "取消成功");
        }else{
            model.addAttribute("errorMsg", "系统出错了");
        }
        return "catalog/main";
    }

    /**
     * 用户要取消订单，返回操作结果
     * @param orderId 用户要取消的order的id
     * @return CommonResponse
     * */
    @PostMapping("/user/deleteOrder")/*用户取消订单*/
    @ResponseBody
    public CommonResponse userDeleteOrder(int orderId){
        return orderService.userDeleteOrder(orderId);
    }

    /**
     * 用户退货，退整个订单的全部货物，返货操作结果
     * @param orderId
     * @return
     */
    @PostMapping("/user/returnOrder")
    @ResponseBody
    public CommonResponse userReturnOrder(int orderId){
        return orderService.userReturnOrder(orderId);
    }
}
